local userId = ARGV[1]
local couponType = ARGV[2]
local stockKey = 'coupon:stock:' .. couponType
local orderKey = 'user:order:' .. couponType

if(redis.call('EXISTS',stockKey)==0) then
    return 3
end
-- 检查库存
if (tonumber(redis.call('get', stockKey)) <= 0) then
    return 1
end

-- 检查集合是否存在
if (redis.call('EXISTS', orderKey) == 0) then
    -- 如果集合不存在，创建集合并添加用户 ID
    redis.call('SADD', orderKey, userId)
    redis.call('incrby', stockKey, -1)
    return 0
end

-- 检查用户是否已下单
if (tonumber(redis.call('SISMEMBER', orderKey, userId)) == 1) then
    return 2
else
    redis.call('SADD', orderKey, userId)
    redis.call('incrby', stockKey, -1)
    return 0
end
